﻿Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Markup


Public MustInherit Class Sprite
    Private _Width As Double
    Public Property Width() As Double
        Get
            Return _Width
        End Get
        Set(ByVal value As Double)
            _Width = value
        End Set
    End Property
    Private _Height As Double
    Public Property Height() As Double
        Get
            Return _Height
        End Get
        Set(ByVal value As Double)
            _Height = value
        End Set
    End Property
    Private _Velocity As Vector
    Public Property Velocity() As Vector
        Get
            Return _Velocity
        End Get
        Set(ByVal value As Vector)
            _Velocity = value
        End Set
    End Property
    Private _SpriteCanvas As Canvas
    Public Property SpriteCanvas() As Canvas
        Get
            Return _SpriteCanvas
        End Get
        Set(ByVal value As Canvas)
            _SpriteCanvas = value
        End Set
    End Property
    Public CollisionRadius As Double
    Private _position As Point
    Public Property Position() As Point
        Get
            Return _position
        End Get
        Set(ByVal value As Point)
            _position = value
            SpriteCanvas.SetValue(Canvas.TopProperty, _position.Y - (Height / 2))
            SpriteCanvas.SetValue(Canvas.LeftProperty, _position.X - (Width / 2))
        End Set
    End Property

    Public Sub New(ByVal initialWidth As [Double], ByVal initialHeight As [Double], ByVal initialPosition As Point)
        Width = initialWidth
        Height = initialHeight

        SpriteCanvas = RenderSpriteCanvas()

        SpriteCanvas.Width = Width
        SpriteCanvas.Height = Height
        'NOTE: because the setter for Position uses both Height and Width, it is important this comes after they are set. 
        Position = initialPosition
        CollisionRadius = Width * 0.48
    End Sub

    Public MustOverride Function RenderSpriteCanvas() As Canvas

    Public Function LoadSpriteCanvas(ByVal xamlPath As String) As Canvas
        Dim s As System.IO.Stream = Me.[GetType]().Assembly.GetManifestResourceStream(xamlPath)
        Return DirectCast(XamlReader.Load(New System.IO.StreamReader(s).ReadToEnd()), Canvas)
    End Function

    Public Overridable Sub Update(ByVal elapsedTime As TimeSpan)
        Position = (Position + Velocity * elapsedTime.TotalSeconds)
    End Sub

    Public Shared Function Collides(ByVal s1 As Sprite, ByVal s2 As Sprite) As Boolean
        Dim v As New Vector((s1.Position.X) - (s2.Position.X), (s1.Position.Y) - (s2.Position.Y))
        If s1.CollisionRadius + s2.CollisionRadius > v.Length Then
            Return True
        Else
            Return False
        End If
    End Function
End Class
